package com.coderman.common.starter.excelport.export.adapter.impl;

import com.coderman.common.starter.excelport.utils.SpringContextUtil;
import com.coderman.common.starter.excelport.export.adapter.IDAOAdapter;
import com.coderman.common.starter.excelport.export.dao.ISqlMapper;
import com.coderman.common.starter.excelport.export.jdbc.ResultSetCallbackHandler;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author fanchunshuai
 * @Date 2019/11/17 22
 * @Description:
 */
@Service
public class MybatisAdapterImpl implements IDAOAdapter {
    //@Autowired
    private ISqlMapper sqlMapper;

    @Autowired
    private ResultSetCallbackHandler resultSetCallbackHandler;



    @Override
    public void registerDAO(Object o) {

    }

    @Override
    public int getCount(String s, Object... objects) throws Exception {
        String sql = getNewSql(s, objects);
        return sqlMapper.getCount(sql);
    }

    @Override
    public List getListBySql(Class<?> aClass, String sql, Object... objects) throws Exception {
        if(aClass == null){
           return sqlMapper.selectList(sql);
        }else {
            SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) SpringContextUtil.getBean("sqlSessionFactory");
            SqlSession sqlSession = sqlSessionFactory.openSession();
            return resultSetCallbackHandler.getExportList(aClass,sqlSession,sql,objects);
        }
    }

    @Override
    public void disRegist() {

    }



    private String getNewSql(String sql,Object... objects){
        if(objects == null){
            return sql;
        }
        String newSql = sql;
        for (Object o : objects){
            if(o instanceof String){
                String strParams = "'" + o.toString()+"'";
                newSql = newSql.replaceFirst("\\?",strParams);
            } else{
                newSql  = newSql.replaceFirst("\\?", o.toString());
            }
        }
        return newSql;
    }
}
